package com.gljx.shiro.rememberMe;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.UsernamePasswordToken;

import com.gljx.constant.Constant;
import com.gljx.util.RSAUtil;

public class MyRememberMe {
	/**
	 * 保存cookie
	 * @throws Exception 
	 */
	//TODO 现在没有用户密码保存cookie要求，此方法暂时闲置
	public static void rememberCookie(UsernamePasswordToken token,ServletRequest  request, 
			ServletResponse response) throws Exception {
		String number = token.getUsername();
		String password = String.valueOf(token.getPassword());
		String host = token.getHost();
		//加密
		String cookieStr = RSAUtil.encry(host,password+"!!!"+number);
		//servlet Cookie
		Cookie cookie = new Cookie(Constant.Cookie_name, cookieStr);
		//存cookie
		cookie.setMaxAge(365*24*60*60);  
		getResponse(response).addCookie(cookie);
	}
	
	/**
	 * 清除cookie
	 */
	//TODO 原因同上
	public static void removeCookie(UsernamePasswordToken token,ServletRequest  request,ServletResponse response) {
		Cookie[] cookies = getRequest(request).getCookies();  
        for (Cookie cookie : cookies) {  
            if (cookie.getName().equals(Constant.Cookie_name)) {  
                cookie.setValue(null);  
                cookie.setMaxAge(0);// 立即销毁cookie  
                //System.out.println("被删除的cookie名字为:" + cookie.getName());
                getResponse(response).addCookie(cookie);  
                break;  
            }  
        }
	}
	public static HttpServletRequest getRequest(ServletRequest request){
		return (HttpServletRequest)request;
	}
	public static HttpServletResponse getResponse(ServletResponse response){
		return (HttpServletResponse)response;
	}
}
